define(function(require, exports, module) {
	require('avalon2');	
	require('resources/js/jquery.json-2.4.min.js');
	require('resources/js/avalon/mmRouter.js');
	
	var moduleMap=require('resources/template/portal/modules.js');
	
	var Workspace=function(config){
		this.getUrl=Common.getUrl.bind(this);
		this.config=$.extend({},Workspace.DEFAULT,config);
		this.$div=$('#workspace');
		
		var that=this;
		$.ajax(this.getUrl('sidebarMenu'),{
			type:'POST',
			dataType:'json'
		}).done(function(data){
			that.data=data;
			that.init();
		}).fail(function(data){
			that.data=[];
			that.init();
		});
	};
	
	Workspace.prototype={
		init:function(){
			this.data.push({href:'#!procinstView',name:'流程实例查看',id:'procinstView'});
			this.initMenuMap();
			//3.工作区，页面切换效果:增加一个内嵌iframe
			this.curPage={};//当前页的组件对象
			//4.路由设置
			this.initRouter();
		},
		initMenuMap:function(){//构造菜单id映射
			//<id,menuItem>
			this.menuItem={};
			var menuItem=this.menuItem;
			var menuMapFn=function(tree,pItem){
				$.map(tree,function(item){
					menuItem[item.id]=item;
					pItem&&(item.pid=pItem.id);
					if(item.children&&item.children.length>0)
						menuMapFn(item.children,item);
				});
			};
			menuMapFn(this.data);
		},
		getHashs:function(){
			//返回菜单里所有的href
			var res=[];
			var getTreeHash=function(tree){
				$.map(tree,function(item){
					res.push(item.href.substr(2));
					if(item.children&&item.children.length>0)
						getTreeHash(item.children);
				});
			};
			getTreeHash(this.data);
			return res;
		},
		directPage:function(menuId,path,params){//工作区页面跳转
			var that=this;
			this.curMenuId=menuId;
			this.itemObj=this.menuItem[menuId];
			document.title=this.itemObj.name;
			//工作区反应
			this.curPage&&that.curPage.destroy&&that.curPage.destroy();
			var Page=moduleMap[menuId];
			Page&&(this.curPage=new Page(this.$div,$.extend(this.config,{
				menuId:menuId,
				path:path,
				params:params
			},params)));
		},
		initRouter:function(){//4.路由设置
			var that=this;
			//添加路由规则
			$.map(this.getHashs(),function(hash){
				avalon.router.add("/"+hash.replace(/\?.*/i,''), function () {
					that.directPage(this.path.substr(1),this.path,this.query);
				});
			});
			//启动路由监听
			avalon.history.start({
			    root: "/"
			});
		},
		urls:{
			sidebarMenu:'/portal/sidebarMenu.jhtml'
		}	
	};	
	
	Workspace.DEFAULT={
			
	};
	
	return  Workspace;
});